<template>
  <section class="component distribute-rule">
    <el-card header="设置分配策略">
      <el-form :model="model" inline label-width="120px" :rules="rules" ref="form">
        <el-form-item label="案件类型" prop="strategyCaseType">
          <el-select v-model="strategyCaseType" placeholder="请选择" clearable @change="strategyCaseTypeChange()" :disabled="isDisabled">
            <el-option v-for="{ code, name } in $dict.getDictData('StrategyCaseType')" :key="code" :label="name" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配策略" prop="assignModel" v-if="model.strategyCaseType === 'OUTSOURCE_TO_COLLECTOR'|| model.strategyCaseType === 'VISIT_TO_COLLECTOR'|| model.strategyCaseType === 'TEL_TO_COLLECTOR'">
          <el-radio-group v-model="model.assignModel" v-if="model.strategyCaseType !== 'OUTSOURCE_TO_COLLECTOR'" placeholder="请选择" clearable :disabled="isDisabled">
            <el-radio v-for="{ code, name } in $dict.getDictData('AssignModel').filter(x=>x.code!=='OUTSOURCE')" :key="code" :label="code">{{name}}</el-radio>
          </el-radio-group>
          <el-radio-group v-model="model.assignModel" v-else placeholder="请选择" clearable :disabled="isDisabled">
            <el-radio v-for="{ code, name } in $dict.getDictData('AssignModel').filter(x=>x.code==='OUTSOURCE')" :key="code" :label="code">{{name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="机构" prop="departmentId" v-if="model.strategyCaseType === 'VISIT_TO_COLLECTOR'|| model.strategyCaseType === 'TEL_TO_COLLECTOR'">
          <el-cascader v-model="departmentIds" :options="deptTreeData" :props="{value:'id',label:'deptName'}" change-on-select :show-all-levels="false" clearable :disabled="isDisabled"></el-cascader>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-if="model.assignModel === 'COLLECTOR'">
      <div slot="header" class="row between-span">
        <span>分配催收员展示</span>
        <el-button @click="dialog.selectUser = true" :disabled="isDisabled">增加</el-button>
      </div>
      <div class="word-pool">
        <div class="row">
          <div class="word" v-for="(item,index) of this.model.userName" :key="index">
            {{item}}
            <a class="del-btn" @click="userDelete(index)">
              <i class="el-icon-circle-close"></i>
            </a>
          </div>
        </div>
      </div>
    </el-card>
    <el-card v-if="model.assignModel === 'OUTSOURCE'">
      <div slot="header" class="row between-span">
        <span>分配受托方展示</span>
        <el-button @click="queryOutSource()" :disabled="isDisabled">增加</el-button>
      </div>
      <div class="word-pool">
        <div class="row">
          <div class="word" v-for="(item,index) of this.model.outsourceName" :key="index">
            {{item}}
            <a class="del-btn" @click="OutsDelete(index)">
              <i class="el-icon-circle-close"></i>
            </a>
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog title="用户选择" width="800px" :center="true" :visible.sync="dialog.selectOutSource" append-to-body>
      <data-box :data="dataSet" :selectionRow.sync="selectionRow" :page="pageService">
        <template slot="columns">
          <!--数据列区域-->
          <el-table-column prop="outsName" label="委外方" :min-width="$helper.getColumnWidth(3)"></el-table-column>
          <el-table-column prop="caseNum" label="案件数量" :min-width="$helper.getColumnWidth(4)"></el-table-column>
          <el-table-column prop="settleNum" label="结清数量" :min-width="$helper.getColumnWidth(4)"></el-table-column>
          <el-table-column prop="successRate" label="历史催收成功率" :min-width="$helper.getColumnWidth(5)" :formatter="row => $filter.toPercent(row.successRate)">
          </el-table-column>
          <el-table-column prop="settleAmount" label="结清总金额(万)" :min-width="$helper.getColumnWidth(4)"></el-table-column>
        </template>
      </data-box>
      <div class="operate-buttons">
        <el-button @click="addOutSource()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户选择" width="800px" :center="true" :visible.sync="dialog.selectUser" append-to-body>
      <user-select :departmentId="model.departmentId" @success="addUser"></user-select>
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Watch, Model } from "vue-property-decorator";
import { Getter } from "vuex-class"
import UserSelect from "./user-select.vue";
import { Form } from "element-ui"
import { OutsourceStayService } from "~/services/domain-service/outsource-stay-manage.service";
import { PageService } from "~/utils/page.service";
import DataBox from "~/components/common/data-box.vue";


@Component({
  components: {
    UserSelect,
    DataBox
  }
})
export default class DistributeRule extends Vue {
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(OutsourceStayService)
  private outsourceStayService: OutsourceStayService;
  @Getter private departmentTreeData
  @Getter private getAllParentId

  @Model('rule-change', {
    required: true,
    type: Object
  })
  private model: any;
  @Prop()
  private isDisabled:any
  private deptTreeData = []
  private usersRealName:any = []
  private isLawsuit:any = false;
  private selectionRow:any= {};

  private dialog = {
    selectUser: false,
    selectOutSource:false
  }
  private dataSet: any[] = []; //受托方列表数据
  private rules = {
    departmentId: { required: true, message: "请选择机构" },
    strategyCaseType: { required: true, message: "请选择分案类型" },
    assignModel: { required: true, message: "请选择分配模式" }
  }

  /**
   * 验证表单数据
   */
  public async validate() {
    const form = this.$refs.form as Form
    const result = await form.validate().catch(() => false)
    let userResult = true
    if (this.model.assignModel === 'COLLECTOR' && !this.model.users.length) {
      this.$message("请选择分配用户")
      userResult = false
    }
    if (result && userResult) {
      this.emitRuleModel(this.model)
      return Promise.resolve()
    } else {
      return Promise.reject('distribute-rule')
    }
  }

  @Emit('rule-change')
  private emitRuleModel(val) { }
  @Emit('strategyCaseTypeChange')
  private strategyCaseTypeChange() {
    console.log(this.model.strategyCaseType,"this.model.strategyCaseType")
    this.model.assignModel = ''
      return this.model.strategyCaseType 
    }
  /**
   * 选中的部门数据
   */
  private get departmentIds() {
    if (!this.model.departmentId) return []
    if (!this.model.strategyCaseType) return []
    const type = this.model.strategyCaseType.split("_")[0]
    return this.getAllParentId(this.model.departmentId, type)
  }
  private set departmentIds(values) {
    let result = ""
    if (values.length) result = values[values.length - 1]
    this.model.departmentId = result
  }
  // 获取委外方id
  private get outsourceIds() {
    return this.selectionRow.outsourceId
  }
  // 获取委外方名称
  private get outsourceName() {
    return this.selectionRow.outsName
  }
  /**
   * 切换部门数据源
   */
  private get strategyCaseType() {
    if (this.model.strategyCaseType) {
      const type = this.model.strategyCaseType.split("_")[0]
      console.log(type,"type")
      this.deptTreeData = this.departmentTreeData(type)
      console.log(this.deptTreeData,"deptTreeData")
    }
    return this.model.strategyCaseType

  }

  private set strategyCaseType(val) {
    this.model.strategyCaseType = val
  }
  //选择受托方
  private queryOutSource(){
    this.dialog.selectOutSource = true
    this.outsourceStayService
      .searchOutsourcePreview(this.isLawsuit, this.pageService)
      .subscribe(data => {
        this.dataSet = data;
      });
  }
  // 删除用户
  private userDelete(index){
    if(this.isDisabled) return
    this.model.users.splice(index,1)
    this.model.userName.splice(index,1)
  }
  
  /**
   * 添加用户
   */
  private addUser(user: any) {
    if (this.model.users.findIndex(x => x === user.id) < 0) {
      this.model.users.push(user.id)
      this.model.userName.push(user.realName)
    }
    this.dialog.selectUser = false
  }
  /**
   * 添加受托方
   */
  private addOutSource() {
    if(!this.selectionRow){
      this.$message("请选择受托方")
      return
    }
    if (this.model.outsourceIds.findIndex(x => x === this.outsourceIds) < 0) {
      this.model.outsourceIds.push(this.outsourceIds)
      this.model.outsourceName.push(this.outsourceName)
    }
    this.dialog.selectOutSource = false 
  }
  // 删除受托方
  private OutsDelete(index){
    if(this.isDisabled) return
    this.model.outsourceIds.splice(index,1)
    this.model.outsourceName.splice(index,1)
  }

  /**
   * 重置
   */
  private reset() {
    const form: any = this.$refs["form"];
    form.resetFields();
  }
}
</script>

<style lang="less" scoped>
.component.distribute-rule {
  .word-pool {
    min-height: 60px;
  }
  .word {
    position: relative;
    min-width: 60px;
    background-color: #f3f3f3;
    padding: 2px 15px 2px 5px;
    border-radius: 3px;
    & ~ {
      margin-right: 10px;
      margin-top: 5px;
    }
    .del-btn {
      display: none;
      position: absolute;
      right: -5px;
      top: -5px;
    }
    &:hover {
      .del-btn {
        display: inline-block;
      }
    }
  }
}
</style>
